﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Newtonsoft.Json;

namespace Treasure.Client
{
    /// <summary>
    /// WinLogin.xaml 的交互逻辑
    /// </summary>
    public partial class WinLogin : Window
    {
        public WinLogin()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(usernaem.Text.Trim()) || string.IsNullOrEmpty(password.Password))
            {
                MessageBox.Show("请输入用户名或密码！", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }
            Uri server = new Uri(String.Format("{0}/{1}/{2}?username={3}&password={4}", CStatic.serviceurl, "users","login",usernaem.Text.Trim(), BitConverter.ToString(MD5.Create().ComputeHash(Encoding.Default.GetBytes(password.Password))).Replace("-", "").ToLower()));
            string result = string.Empty;
            try
            {
                HttpResponseMessage response;

                response = HttpClientFactory.HttpClient.PostAsync(server, null).Result;
                if (response.IsSuccessStatusCode)
                {
                    result= response.Content.ReadAsStringAsync().Result;
                    CStatic.user= JsonConvert.DeserializeObject<User>(result);                    
                    this.DialogResult = true;
                    this.Close();
                }
                else
                {
                    msg.Text = "用户不存在或用户名密码错误！";
                }
            }
            catch (Exception ex)
            {
                msg.Text = ex.Message;
            }
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (this.DialogResult == null)
                this.DialogResult = false;
        }

        private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if(e.Key == System.Windows.Input.Key.Enter)
                Button_Click(null, null);
        }
    }
}
